<template>
  <div>
    <el-button type="primary" icon="el-icon-edit" plain style="margin-bottom: 20px" @click="hdlOpen(newForm)">
      {{ textMap['create'] }}
    </el-button>
    <el-card shadow="hover" :body-style="{ padding: '0px' }">

      <u-table
        :data="list"
        :page="false"
        :columns="columns"
        :options="{ headerCellStyle: { background:'#FAFAFA'}, stripe: true }"
      >
        <template v-slot:right>

          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="{ row }">
              <el-button type="text" @click="hdlEdit(row)">编辑</el-button>
              <el-button type="text" @click="hdlDelete(row)">删除</el-button>
            </template>
          </el-table-column>

        </template>
      </u-table>

    </el-card>

    <u-dialog :title="textMap[dialogStatus]" :show.sync="dialogFormVisible" :append-to-body="true" @confirm="dialogStatus==='create'?hdlCreate():hdlUpdate()">
      <el-form ref="dialogForm" :rules="rules" :model="dataForm" label-width="100px">
        <el-form-item label="日期类型" prop="type">
          <el-radio-group v-model="dataForm.type">
            <el-radio :label="1">年</el-radio>
            <el-radio :label="0">日</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="目标卡类型" prop="targetLevel">
          <level v-model="dataForm.targetLevel" />
        </el-form-item>
        <el-form-item label="最小金额" prop="minAmount">
          <el-input v-model="dataForm.minAmount" />
        </el-form-item>
        <el-form-item label="最大金额" prop="maxAmount">
          <el-input v-model="dataForm.maxAmount" />
        </el-form-item>
      </el-form>
    </u-dialog>

  </div>

</template>

<script>
import level from '@/components/member/level'
/**
 * 业务组件 - 奖品设置组件
 */
export default {
  name: 'Rule',
  components: {
    level
  },
  props: {
    /** 数据源 */
    value: {
      type: [Array, String],
      default() {
        return []
      }
    }
  },
  data() {
    return {
      // 选择的会员
      columns: [
        {
          prop: 'type',
          label: '日期类型',
          formatter: (row) => {
            if (row.type === 0) {
              return '日'
            } else if (row.type === 1) {
              return '年'
            }
          }
        },
        {
          prop: 'targetLevel',
          label: '目标等级',
          render: (h, params) => {
            const { targetLevel } = params.row
            if (targetLevel === '104') {
              return h('el-tag', { props: { type: 'success' }}, '微会员')
            } else if (targetLevel === '101') {
              return h('el-tag', { props: { type: 'success' }}, '金卡')
            } else if (targetLevel === '102') {
              return h('el-tag', { props: { type: 'success' }}, '红宝石卡')
            } else if (targetLevel === '103') {
              return h('el-tag', { props: { type: 'success' }}, '钻石卡')
            }
          }
        },
        {
          prop: 'minAmount',
          label: '最小金额'
        },
        {
          prop: 'maxAmount',
          label: '最大金额'
        }
      ],
      // 选中的等级
      list: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑规则',
        create: '新增规则'
      },
      dataForm: {
      },
      rules: {
        type: [
          { required: true, message: '日期类型必选', trigger: 'change' }
        ],
        targetLevel: [
          { required: true, message: '目标等级必选', trigger: ['blur'] }
        ],
        minAmount: [
          { required: true, message: '最小金额必填', trigger: ['blur'] }
        ],
        maxAmount: [
          { required: true, message: '最大金额必填', trigger: ['blur'] }
        ]
      },
      // 删除选中数据
      selectData: [],
      newForm: {
      }
    }
  },
  watch: {
    // 监听数据
    value: {
      immediate: true,
      handler(val) {
        // 初始化数据
        this.loadData(val)
      }
    }
  },
  methods: {
    // 初始化数据
    async loadData(val) {
      if (val) {
        if (typeof this.value === 'string') {
          try {
            this.list = JSON.parse(this.value)
          } catch (error) {
            console.error('Invalid JSON string:', this.value)
            this.list = []
          }
        }
      }
    },
    // 通知数据更新
    change() {
      const { list } = this
      this.$emit('input', JSON.stringify(list))
      this.$emit('change', JSON.stringify(list))
    },
    /**
     * 打开新增窗口事件
     * @param row
     */
    hdlOpen(row) {
      const self = this
      // 初始化数据源
      self.dataForm = Object.assign({}, row)
      // 打开新增状态
      self.dialogStatus = 'create'
      // 打开弹框状态
      self.dialogFormVisible = true
      // 清除表单验证状态
      self.$nextTick(() => {
        self.$refs['dialogForm'].clearValidate()
      })
    },
    // 编辑事件
    hdlEdit(row) {
      const self = this
      // 初始化数据源
      self.dataForm = Object.assign({}, row)
      // 打开编辑状态
      self.dialogStatus = 'update'
      // 打开弹框状态
      self.dialogFormVisible = true
      // 清除表单验证状态
      self.$nextTick(() => {
        self.$refs['dialogForm'].clearValidate()
      })
    },
    /**
     * 提交创建数据事件
     */
    hdlCreate() {
      const self = this
      // 效验数据格式
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          // 获取最大 ID 值
          const maxId = self.list.length > 0 ? Math.max(...self.list.map(item => item.id)) : 0
          // 添加id
          self.dataForm.id = maxId + 1
          self.dataForm.createTime = self.$u.timeFormat(Date.now())
          // 添加数据
          self.list.push(self.dataForm)
          // 关闭弹窗状态
          self.dialogFormVisible = false
          // 通知数据更新
          self.change()
        }
      })
    },
    /**
     * 提交更新数据事件
     */
    hdlUpdate() {
      const self = this
      // 效验数据格式
      self.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          // 添加数据
          const { id } = self.dataForm
          const foundIndex = self.list.findIndex(item => item.id === id)
          if (foundIndex !== -1) {
            self.dataForm.createTime = self.$u.timeFormat(Date.now())
            // 替换列表中指定索引的对象
            self.list[foundIndex] = { ...self.dataForm }
          }
          // 关闭弹窗状态
          self.dialogFormVisible = false
          // 通知数据更新
          self.change()
        }
      })
    },
    /**
     * 删除单个事件
     * @param row
     */
    hdlDelete(row) {
      const self = this
      // 模态对话框组件
      self.$confirm('确认删除该规则吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        // 处理确认事件
        self.list.splice(self.list.findIndex(item => item.id === row.id), 1)
        // 通知数据更新
        self.change()
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep{
  .el-input{
    width: 100% !important;
  }
}
</style>
